package iagovsothello.gui;
import iagovsothello.logger.Experiment;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;

public class ProgressDialog extends javax.swing.JDialog implements Observer {
	
	private static final long serialVersionUID = -4656986746145197021L;
	private JProgressBar progressBar;
	private JLabel labelProgress;
	private JLabel labelInfo;

	private Experiment experiment;
	private int size;
	private int value;
	
	public ProgressDialog(JFrame frame) 
	{
		super(frame);
		initGUI();
	}
	
	public ProgressDialog(JFrame frame, Experiment experiment) 
	{
		super(frame);
		this.experiment = experiment;
		this.size = experiment.totalSize();
		
		initGUI();
		initBar();

		this.experiment.addObserverRecursive(this);
	}
	
	private void initGUI()
	{
		GridBagLayout thisLayout = new GridBagLayout();
		thisLayout.rowWeights = new double[] {0.1, 0.1, 0.1, 0.1, 0.1};
		thisLayout.rowHeights = new int[] {7, 20, 7, 7, 7};
		thisLayout.columnWeights = new double[] {0.0, 0.1, 0.1, 0.0};
		thisLayout.columnWidths = new int[] {30, 7, 7, 30};
		getContentPane().setLayout(thisLayout);
		this.setTitle("Esperimento");

		progressBar = new JProgressBar();
		getContentPane().add(progressBar, new GridBagConstraints(1, 2, 2, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));

		labelProgress = new JLabel();
		getContentPane().add(labelProgress, new GridBagConstraints(1, 3, 2, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
		labelProgress.setText("0");

		labelInfo = new JLabel();
		getContentPane().add(labelInfo, new GridBagConstraints(1, 1, 2, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
		labelInfo.setText("Esperimento in corso...");

		this.setSize(440, 175);
		this.setResizable(false);
	}

	public void start()
	{
		SwingUtilities.invokeLater(new ExperimentRunner());
	}
	
	@Override
	public void update(Observable o, Object arg) 
	{
		value++;
		progressBar.setValue(value);
		labelProgress.setText("Partite svolte: "+value+"/"+size);
		if (value >= size)
		{
			dispose();
		}
	}

	private void initBar()
	{
		if (experiment != null)
		{
			value = 0;
			
			progressBar.setMaximum(size);
			progressBar.setValue(0);
			progressBar.setIndeterminate(false);
			
			labelProgress.setText("Partite svolte: 0/"+size);
		}
		else
		{
			progressBar.setIndeterminate(true);
		}
	}
	
	private class ExperimentRunner implements Runnable {

		@Override
		public void run() 
		{
			experiment.start();
		}
		
	}
}
